<?php
/**
 * 
 * Sitemap module
 * 
 * @name			Sitemap
 * @description		Standard sitemap module for Cosa admin
 * @version			1.0.0
 * 
 * @author			Stijn Van Minnebruggen
 * @author_url		www.donotfold.be
 * @module_url		www.donotfold.be/projects/cosa
 * 
 * @sub1			pages
 * @sub2			nav
 * @sub3			fus
 * 
 */

// @sub3			skins (disabled)

class sitemap extends Module
{
	
	
	/**
	 * Install script for module
	 * 
	 * @return	bool
	 */
	
	public function install($die=false)
	{
		// required
			global $cosa, $db;
		
		// create pages table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('pages')."` (
					`id` int(11) NOT NULL auto_increment,
					`name` varchar(255) NOT NULL,
					`language_id` int(11) NOT NULL,
					`skin_id` int(11) NOT NULL,
					`title` varchar(255) NOT NULL,
					`text` text NOT NULL,
					`meta_title` varchar(255) NOT NULL,
					`meta_keywords` varchar(255) NOT NULL,
					`meta_description` varchar(255) NOT NULL,
					`original_id` int(11) NOT NULL,
					`published` enum('0','1') NOT NULL default '0',
					`created_by` int(11) NOT NULL,
					`time_created` datetime NOT NULL,
					`deleted` enum('1','0') NOT NULL default '0',
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM;
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (1).', 'db');
				else return false;
			}
		
		// create navigations table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('pages_nav')."` (
					`id` int(11) NOT NULL auto_increment,
					`language_id` int(11) NOT NULL,
					`title` varchar(255) NOT NULL,
					`type` enum('int','ext','nav') NOT NULL default 'int',
					`page_original_id` int(11) NOT NULL,
					`ext_url` varchar(255) NOT NULL,
					`ext_target` varchar(255) NOT NULL,
					`parent_id` int(11) NOT NULL default '0',
					`weight` int(11) NOT NULL,
					`protected` enum('1','0') NOT NULL default '0',
					`is_local` enum('1','0') NOT NULL default '0',
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (2).', 'db');
				else return false;
			}
		
		// create skins table
			$sql = "CREATE TABLE IF NOT EXISTS `".$db->module('pages_skins')."` (
					`id` int(11) NOT NULL auto_increment,
					`name` varchar(255) NOT NULL,
					`active` enum('1','0') NOT NULL default '1',
					PRIMARY KEY  (`id`)
					) ENGINE=MyISAM
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (3).', 'db');
				else return false;
			}
		
		// insert default skin
			$sql = "INSERT INTO `".$db->module('pages_skins')."` SET name = 'Default'";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (4).', 'db');
				else return false;
			}
		
		// create fus table
			$sql = "CREATE TABLE `".$db->module('pages_fus')."` (
					  `id` int(11) NOT NULL auto_increment,
					  `key` varchar(255) NOT NULL,
					  `value` text NOT NULL,
					  `language_id` int(11) NOT NULL,
					  PRIMARY KEY  (`id`)
					) ENGINE=MyISAM
					";
			if(!@mysql_query($sql)) {
				if($die) $cosa->oops('Could not install pages module (5).', 'db');
				else return false;
			}
		
		// return success
			return true;
		
	}
	
	
	/**
	 * Uninstall script for module
	 * 
	 * @return	bool
	 */
	
	public function uninstall()
	{
		global $cosa;
		$sql = "DROP TABLE `".$db->module('pages')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (1).', 'db');
		$sql = "DROP TABLE `".$db->module('pages_nav')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (2).', 'db');
		$sql = "DROP TABLE `".$db->module('pages_skins')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (3).', 'db');
		$sql = "DROP TABLE `".$db->module('pages_fus')."`";
		@mysql_query($sql) or $cosa->oops('Could not uninstall pages module (4).', 'db');
		return true;
	}
	
	
	/**
	 * Constructor function
	 * 
	 * @return void
	 */
	
	public function __construct()
	{
		parent::__construct();
		if(isset($_REQUEST['publish']) && !isset($_REQUEST['edit']) && !isset($_REQUEST['add'])) $this->publish($_REQUEST['publish']);
	}
	
	
	/**
	 * Add a page
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function pages_add($postVars)
	{
		// required
			global $cosa, $db, $user, $lang, $path, $modules;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-page-failed'));
				return false;
			}
		
		// publish
			$publish = (isset($postVars['publish']) && $this->settings('sitemap-can-publish')) ? 1 : 0;		
		// add page
			$sql = "INSERT INTO ".$db->module('pages')."
					SET	name				= '".addslashes($postVars['name'])."'
						,language_id		= '".$lang->id."'
						,skin_id			= '".addslashes($postVars['skin_id'])."'
						,title				= '".addslashes($postVars['title'])."'
						,text				= '".addslashes($postVars['text'])."'
						,meta_title			= '".addslashes($postVars['meta_title'])."'
						,meta_keywords		= '".addslashes($postVars['meta_keywords'])."'
						,meta_description	= '".addslashes($postVars['meta_description'])."'
						,published			= '".$publish."'
						,created_by			= '".addslashes($user->id())."'
						,time_created		= NOW()
					";
			@mysql_query($sql) or $cosa->kill($lang->get('add-page-failed'), 'db');
			$page_id = mysql_insert_id();
		
		// update insert id
			$sql = "UPDATE ".$db->module('pages')." SET original_id = '".addslashes($page_id)."' WHERE id = '".addslashes($page_id)."'";
			@mysql_query($sql) or $cosa->kill($lang->get('add-page-failed'), 'db');
		
		// set nav vars
			$protected = (isset($postVars['protected'])) ? 1 : 0;
			$nav = array('title'				=> addslashes($postVars['nav_title'])
						,'type'					=> 'int'
						,'page_original_id'		=> $page_id
						,'ext_url'				=> ''
						,'ext_target'			=> ''
						,'parent_id'			=> addslashes($postVars['nav_parent_id'])
						,'weight'				=> addslashes($postVars['nav_weight'])
						,'protected'			=> $protected
						);
			if(!empty($postVars['nav_title'])) $this->nav_add($nav);
		
		// save path
			$myPath = (!empty($postVars['path'])) ? $postVars['path'] : $postVars['title'];
			if($myPath) $path->create($myPath, $db->module('pages'), $lang->id, $page_id);
		
		// return success
			$modules->addMessage($lang->get('add-page-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a page
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function pages_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $lang, $path, $modules;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-page-failed'));
				return false;
			}
		
		// get original id
			$sql = "SELECT original_id FROM ".$db->module('pages')." WHERE id = '".addslashes($id)."'";
			$res = @mysql_query($sql) or $cosa->kill($lang->get('edit-page-failed'), 'db');
			$row = mysql_fetch_array($res);
			$original_id = stripslashes($row['original_id']);
		
		// publish
			$publish = (isset($postVars['publish']) && $this->settings('sitemap-can-publish')) ? 1 : 0;
		
		// add page
			$sql = "INSERT INTO ".$db->module('pages')."
					SET	name				= '".addslashes($postVars['name'])."'
						,language_id		= '".$lang->id."'
						,skin_id			= '".addslashes($postVars['skin_id'])."'
						,title				= '".addslashes($postVars['title'])."'
						,text				= '".addslashes($postVars['text'])."'
						,meta_title			= '".addslashes($postVars['meta_title'])."'
						,meta_keywords		= '".addslashes($postVars['meta_keywords'])."'
						,meta_description	= '".addslashes($postVars['meta_description'])."'
						,original_id		= '".addslashes($original_id)."'
						,published			= '".$publish."'
						,created_by			= '".addslashes($user->id())."'
						,time_created		= NOW()
					";
			@mysql_query($sql) or $cosa->kill($lang->get('add-page-failed'), 'db');
			$page_id = mysql_insert_id();
		
		// unpublish others if needed
			if($publish) $this->publish($page_id);			
		
		// set nav vars
			$protected = (isset($postVars['protected'])) ? 1 : 0;
			$nav = array('title'				=> addslashes($postVars['nav_title'])
						,'type'					=> 'int'
						,'page_original_id'		=> addslashes($original_id)
						,'ext_url'				=> ''
						,'ext_target'			=> ''
						,'parent_id'			=> addslashes($postVars['nav_parent_id'])
						,'weight'				=> addslashes($postVars['nav_weight'])
						,'protected'			=> $protected
						);
		
		// add or edit navigation
			if(isset($postVars['nid'])) {
				if(empty($postVars['nav_title'])) {
					$this->nav_del($postVars['nid']);
				} else {
					$nav['edit'] = addslashes($postVars['nid']);
					$this->nav_edit($nav, addslashes($postVars['nid']));
				}
			} else if(!empty($postVars['nav_title'])) {
				$this->nav_add($nav);
			}
		
		// save path
			$myPath = (!empty($postVars['path'])) ? $postVars['path'] : $postVars['title'];
			if($myPath) $path->create($myPath, $db->module('pages'), $lang->id, $original_id);
		
		// return success
			$modules->addMessage($lang->get('edit-page-success'));
			return true;
		
	}
	
	
	/**
	 * Delete a page
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function pages_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang, $path;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-page-failed'));
				return false;
			}
		
		// delete page
			$sql = "UPDATE ".$db->module('pages')." SET deleted = '1' WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-page-failed'), 'db');
		
		// delete all navigation items related to this page
			$original_id = $this->getOriginalId($id);
			if($original_id) {
				$sql = "DELETE FROM ".$db->module('pages_nav')." WHERE type='int' AND page_original_id = '".addslashes($original_id)."'";
				@mysql_query($sql) or $cosa->kill($lang->get('del-nav-failed'), 'db');
			}
		
		// add message to pool
			$modules->addMessage($lang->get('del-page-success'));
			return true;
		
	}
	
	
	/**
	 * Get one page
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function pages_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Get the published version of a page
	 * 
	 * @param	int		$original_id
	 * @return	array
	 */
	
	public function pages_get_published($original_id)
	{
		// required
			global $cosa, $db;
			if(!isset($original_id) || empty($original_id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages')." WHERE original_id ='".addslashes($original_id)."' AND published = '1' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Edit a page
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function history_edit($postVars, $id)
	{
		return $this->pages_edit($postVars, $id);
	}
	
	
	/**
	 * Add a navigation
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function nav_add($postVars)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-nav-failed'));
				return false;
			}
		
		// password protected
			$protected = ($postVars['protected'] == '1') ? 1 : 0;
			$is_local = ($postVars['is_local'] == '1') ? 1 : 0;
		
		// create query
			$sql = "INSERT INTO ".$db->module('pages_nav')."
					SET	language_id				= '".addslashes($lang->id)."'
						,title					= '".addslashes($postVars['title'])."'
						,type					= '".addslashes($postVars['type'])."'
						,page_original_id		= '".addslashes($postVars['page_original_id'])."'
						,ext_url				= '".addslashes($postVars['ext_url'])."'
						,ext_target				= '".addslashes($postVars['ext_target'])."'
						,parent_id				= '".addslashes($postVars['parent_id'])."'
						,weight					= '".addslashes($postVars['weight'])."'
						,protected				= '".addslashes($protected)."'
						,is_local				= '".addslashes($is_local)."'
					";
		
		// execute query
			@mysql_query($sql) or $cosa->kill($lang->get('add-nav-failed'), 'db');
			$modules->addMessage($lang->get('add-nav-success'));
		
		// update local navigation image
			$this->updateNavImage();
			return true;
		
	}
	
	
	/**
	 * Edit a navigation
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function nav_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-nav-failed'));
				return false;
			}
		
		// password protected
			$protected = ($postVars['protected'] == '1') ? 1 : 0;
			$is_local = ($postVars['is_local'] == '1') ? 1 : 0;
		
		// create query
			$sql = "UPDATE ".$db->module('pages_nav')."
					SET	title				= '".addslashes($postVars['title'])."'
						,type				= '".addslashes($postVars['type'])."'
						,page_original_id	= '".addslashes($postVars['page_original_id'])."'
						,ext_url			= '".addslashes($postVars['ext_url'])."'
						,ext_target			= '".addslashes($postVars['ext_target'])."'
						,parent_id			= '".addslashes($postVars['parent_id'])."'
						,weight				= '".addslashes($postVars['weight'])."'
						,protected			= '".addslashes($protected)."'
						,is_local			= '".addslashes($is_local)."'
					WHERE
						id					= '".addslashes($postVars['edit'])."'
					";
		
		// execute query
			@mysql_query($sql) or $cosa->kill($lang->get('edit-nav-failed'), 'db');
			$modules->addMessage($lang->get('edit-nav-success'));
		
		// update local navigation image
			$this->updateNavImage();
			return true;
		
	}
	
	
	/**
	 * Delete a navigation
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function nav_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-nav-failed'));
				return false;
			}
		
		// execute query
			$sql = "DELETE FROM ".$db->module('pages_nav')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-nav-failed'), 'db');
		
		// update children
			$sql = "UPDATE ".$db->module('pages_nav')." SET parent_id = '0' WHERE parent_id='".addslashes($id)."'";
			@mysql_query($sql) or $cosa->kill($lang->get('del-nav-failed'), 'db');
		
		// update local navigation image
			$this->updateNavImage();
		
		// add message to pool
			$modules->addMessage($lang->get('del-nav-success'));
			return true;
		
	}
	
	
	/**
	 * Get one navigation
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function nav_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages_nav')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Update navigation image
	 * 
	 * @param	string	$var
	 * @return	bool
	 */
	
	public function updateNavImage()
	{
		// require
			global $cosa, $db, $lang, $m;
		
		// fetch first navigation
			$sql = "SELECT title FROM ".$db->module('pages_nav')." WHERE language_id = '".addslashes($lang->id)."' AND parent_id = '0' ORDER BY weight LIMIT 1";
			$res = mysql_query($sql) or $cosa->kill('Could not update navigation image.', 'db');
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
		
		// new location
			$newPath = $cosa->system('root_path').'img/lang/'.$lang->domain_short.'/'.$lang->short.'/nav-local.png';
		
		// settings
			$text = strtoupper(stripslashes($row['title']));
			$width = 300;
			$height = 80;
			$quality = 100;
		
		// colors
			$white = array('r' => 255, 'g' => 255, 'b' => 255);
			$orange = array('r' => 240, 'g' => 139, 'b' => 29);
			$green = array('r' => 140, 'g' => 198, 'b' => 63);
		
		// font
			$fontFace = 'BreeChiquitaRegular.otf';
			$fontSize = 10;
			$fontAngle = 0;
			$fontX = 10;
			$fontY = 21;
			$fontY2 = 71;	
		
		// init settings
			$fontPath = realpath('.').'/modules/sitemap/font/';
			putenv('GDFONTPATH='.$fontPath);
			$im  = imagecreatetruecolor($width, $height);
			if(function_exists('imageantialias')) imageantialias($im, TRUE);
			$clr_white = imagecolorallocate($im, $white['r'], $white['g'], $white['b']);
			$clr_orange = imagecolorallocate($im, $orange['r'], $orange['g'], $orange['b']);
			$clr_green = imagecolorallocate($im, $green['r'], $green['g'], $green['b']);
		
		// generate image
			imagefilledrectangle($im, 0, 0, $width, $height, $clr_white);
			imagettftext($im, $fontSize, $fontAngle, $fontX, $fontY, $clr_orange, $fontFace, $text);
			imagettftext($im, $fontSize, $fontAngle, $fontX, $fontY2, $clr_green, $fontFace, $text);
		
		// save image
			//imagejpeg($im, $newPath, $quality);
			imagepng($im, $newPath);
			imagedestroy($im);
		
	}
	
	
	/**
	 * Add a fus
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function fus_add($postVars)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-fus-failed'));
				return false;
			}
		
		// create query
			$sql = "INSERT INTO ".$db->module('pages_fus')."
					SET	language_id			= '".addslashes($lang->id)."'
						,`key`				= '".addslashes($postVars['key'])."'
						,value				= '".addslashes($postVars['value'])."'
					";
		
		// execute query
			@mysql_query($sql) or $cosa->kill($lang->get('add-fus-failed'), 'db');
			$modules->addMessage($lang->get('add-fus-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a fus
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function fus_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-fus-failed'));
				return false;
			}
		
		// create query
			$sql = "UPDATE ".$db->module('pages_fus')."
					SET	language_id			= '".addslashes($lang->id)."'
						,`key`				= '".addslashes($postVars['key'])."'
						,value				= '".addslashes($postVars['value'])."'
					WHERE
						id					= '".addslashes($postVars['edit'])."'
					";
		
		// execute query
			@mysql_query($sql) or $cosa->kill($lang->get('edit-fus-failed'), 'db');
			$modules->addMessage($lang->get('edit-fus-success'));
			return true;
		
	}
	
	
	/**
	 * Delete a fus
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function fus_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-fus-failed'));
				return false;
			}
		
		// execute query
			$sql = "DELETE FROM ".$db->module('pages_fus')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-fus-failed'), 'db');
		
		// add message to pool
			$modules->addMessage($lang->get('del-fus-success'));
			return true;
		
	}
	
	
	/**
	 * Get one fus
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function fus_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages_fus')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Add a skin
	 * 
	 * @param	array	$postVars
	 * @return	bool
	 */
	
	public function skins_add($postVars)
	{
		// required
			global $cosa, $db, $user, $lang, $path, $modules;
			if(!isset($postVars) || empty($postVars)) {
				$modules->addMessage($lang->get('add-skin-failed'));
				return false;
			}
		
		// add page
			$sql = "INSERT INTO ".$db->module('pages_skins')."
					SET	name			= '".addslashes($postVars['name'])."'
						,active			= '".addslashes($postVars['active'])."'
					";
			@mysql_query($sql) or $cosa->kill($lang->get('add-skin-failed'), 'db');
			$page_id = mysql_insert_id();
		
		// return success
			$modules->addMessage($lang->get('add-skin-success'));
			return true;
		
	}
	
	
	/**
	 * Edit a skin
	 * 
	 * @param	array	$postVars
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function skins_edit($postVars, $id)
	{
		// required
			global $cosa, $db, $user, $lang, $path, $modules;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('edit-skin-failed'));
				return false;
			}
		
		// add skin
			$sql = "UPDATE ".$db->module('pages_skins')."
					SET	name			= '".addslashes($postVars['name'])."'
						,active			= '".addslashes($postVars['active'])."'
					WHERE id			= '".addslashes($id)."'
					";
			@mysql_query($sql) or $cosa->kill($lang->get('edit-skin-failed'), 'db');
			$page_id = mysql_insert_id();
		
		// return success
			$modules->addMessage($lang->get('edit-skin-success'));
			return true;
		
	}
	
	
	/**
	 * Delete a skin
	 * 
	 * @param	int		$id
	 * @return	bool
	 */
	
	public function skins_del($id)
	{
		// required
			global $cosa, $db, $modules, $lang, $path;
			if(!isset($id) || empty($id)) {
				$modules->addMessage($lang->get('del-skin-failed'));
				return false;
			}
		
		// check number of pageskins, there must be one left
			$sql = "SELECT COUNT(*) AS num FROM ".$db->module('pages_skins');
			$res = mysql_query($sql) or $cosa->kill($lang->get('del-skin-failed'), 'db');
			$row = mysql_fetch_array($res);
			if($row['num'] <= 1) {
				$modules->addMessage($lang->get('del-skin-lastnotdeleted'));
				return false;
			}
		
		// delete page
			$sql = "DELETE FROM ".$db->module('pages_skins')." WHERE id ='".addslashes($id)."' LIMIT 1";
			@mysql_query($sql) or $cosa->kill($lang->get('del-skin-failed'), 'db');
		
		// add message to pool
			$modules->addMessage($lang->get('del-skin-success'));
			return true;
		
	}
	
	
	/**
	 * Get one skin
	 * 
	 * @param	int		$id
	 * @return	array
	 */
	
	public function skins_get($id)
	{
		// required
			global $cosa, $db;
			if(!isset($id) || empty($id)) return false;
		
		// execute query
			$sql = "SELECT * FROM ".$db->module('pages_skins')." WHERE id ='".addslashes($id)."' LIMIT 1";
			$res = @mysql_query($sql) or $cosa->oops('Could not fetch item.', 'db');
		
		// return result
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Print navigation dropdown
	 * 
	 * @param	string	$name
	 * @param	int		$selected_id
	 * @param	int		$excludeId
	 * @return	void
	 */
	
	public function printNavDropdown($name, $selected_id=false, $excludeId=false)
	{
		// required
			global $cosa, $db, $lang;
			$this->_dashChar = '&mdash;';
			$this->_dashes = 1;
		
		// start select
			echo '<select name="'.$name.'">'."\n";
			echo "\t".'<option value="">'.$lang->get('nav-none').'</option>'."\n";
		
		// print navigation children
			$this->_printNavChildren(0, $selected_id, $excludeId);
		
		// close select
			echo '</select>'."\n";
		
	}
	
	
	/**
	 * Print navigation children for dropdown (recursive function)
	 * 
	 * @param	int		$parent_id
	 * @param	int		$selected_id
	 * @param	int		$includeOwnID
	 * @return	void
	 */
	
	private function _printNavChildren($parent_id, $selected_id=false, $excludeId=false)
	{
		// fetch children
			global $cosa, $db, $lang;
			$sql = "SELECT id, title FROM ".$db->module('pages_nav')." WHERE parent_id = '".$parent_id."' AND language_id='".$lang->id."' ORDER BY weight";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch pages.');
		
		// no results, stop recursive loop
			if(!mysql_num_rows($res)) return false;
			else $this->_dashes++;
		
		// reset dashes
			if($parent_id == 0) $this->_dashes = 0;
		
		// print children
			while($row = mysql_fetch_array($res)) {
				
				if(!$excludeId || ($excludeId && $row['id'] != $excludeId)) {
					
					// print row
						$selected = ($selected_id == $row['id']) ? ' selected="selected"' : '';
						echo '<option value="'.$row["id"].'"'.$selected.'>';
						for($i=0; $i<$this->_dashes; $i++) echo $this->_dashChar;
						echo ' '.stripslashes($row['title']);
						echo '</option>'."\n";
					
					// print children
						$this->_printNavChildren($row['id'], $selected_id, $excludeId);
					
				}
				
			}
		
		// remove one dash
			if($this->_dashes > 0) $this->_dashes--;
		
	}
	
	
	/**
	 * Check if navigation has children
	 * 
	 * @param	int		$nav_id
	 * @return	bool
	 */
	
	public function navHasChildren($nav_id)
	{
		global $cosa, $db;
		$sql = "SELECT id FROM ".$db->module('pages_nav')." WHERE parent_id = '".$nav_id."' LIMIT 1";
		$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch children.');
		return (mysql_num_rows($res)) ? true : false;
	}
	
	
	/**
	 * Get navigation from page id
	 * 
	 * @param	int		$page_id
	 * @return	array
	 */
	
	public function getNavFromPageId($page_id)
	{
		// fetch page
			global $cosa, $db, $lang;
			$original_id = $this->getOriginalId($page_id);
			$sql = "SELECT id, title, weight, parent_id, is_local FROM ".$db->module('pages_nav')." WHERE page_original_id = '".addslashes($original_id)."' AND language_id='".$lang->id."' LIMIT 1";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch navigation.');
		
		// return data
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res);
			return $row;
		
	}
	
	
	/**
	 * Print pages dropdown
	 * 
	 * @param	string	$name
	 * @param	int		$original_id
	 * @return	void
	 */
	
	public function printPagesDropdown($name, $original_id=false)
	{
		// required
			global $cosa, $db, $lang;
		
		// start select
			echo '<select name="'.$name.'">'."\n";
			echo "\t".'<option value="">'.$lang->get('nav-none').'</option>'."\n";
		
		// first, fetch pages without navigation
			$sql = "SELECT original_id, title FROM ".$db->module('pages')." WHERE published = '1' AND deleted='0' AND language_id='".$lang->id."' ORDER BY title";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch pages.');
			while($row = mysql_fetch_array($res)) {
				
				// print row
					$selected = ($original_id == $row['original_id']) ? ' selected="selected"' : '';
					echo '<option value="'.$row["original_id"].'"'.$selected.'>';
					echo stripslashes($row["title"]);
					echo '</option>'."\n";
				
			}
		
		// close select
			echo '</select>'."\n";
		
	}
	
	
	/**
	 * Check if there are newer, unpublished pages, if so, return id
	 * 
	 * @param	int		$id
	 * @return	int
	 */
	
	public function hasUnpublished($id)
	{
		// required
			global $cosa, $db;
		
		// get values
			$sql = "SELECT id, original_id, time_created FROM ".$db->module('pages')." WHERE id = '".addslashes($id)."'";
			$res = mysql_query($sql) or $cosa->kill('Could not fetch unpublished pages (1).', 'db');
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res, MYSQL_ASSOC);
		
		// check for newer
			$sql = "SELECT id FROM ".$db->module('pages')." WHERE original_id = '".addslashes($row['original_id'])."' AND time_created > '".addslashes($row['time_created'])."' AND published = '0' ORDER BY time_created DESC LIMIT 1";
			$res = mysql_query($sql) or $cosa->oops('Could not fetch unpublished pages (2).', 'db');
			if(!mysql_num_rows($res)) return false;
			$row = mysql_fetch_array($res, MYSQL_ASSOC);
			return stripslashes($row['id']);
		
	}
	
	
	/**
	 * Check if user can publish
	 * 
	 * @return	bool
	 */
	
	public function userCanPublish()
	{
		global $user;
		$group_ids = $this->settings('sitemap-can-publish');
		if(!$group_ids) return false;
		$group_ids = split(',', $group_ids);
		return in_array($user->group_id, $group_ids);
	}
	
	
	/**
	 * Publish a page
	 * 
	 * @param	int			$page_id
	 * @return	bool
	 */
	
	public function publish($page_id)
	{
		// required
			global $cosa, $db, $lang, $modules;
		
		// check permissions
			if($this->userCanPublish()) {
				
				// get original page id
					$sql = "SELECT original_id FROM ".$db->module('pages')." WHERE id = '".addslashes($page_id)."'";
					$res = mysql_query($sql) or $cosa->kill($lang->get('publish-failed').' (A)', 'db');
					$row = mysql_fetch_array($res);
					if(!mysql_num_rows($res)) $cosa->kill($lang->get('publish-failed').' (B)');
					$oid = stripslashes($row['original_id']);
				
				// unpublish all pages
					$sql = "UPDATE ".$db->module('pages')." SET published = '0' WHERE original_id = '".addslashes($oid)."'";
					mysql_query($sql) or $cosa->kill($lang->get('publish-failed').' (C)', 'db');
				
				// publish new page
					$sql = "UPDATE ".$db->module('pages')." SET published = '1' WHERE id = '".addslashes($page_id)."'";
					mysql_query($sql) or $cosa->kill($lang->get('publish-failed').' (D)', 'db');
				
				// thanks
					$modules->addMessage($lang->get('publish-success'));
					return true;
				
			} else {
				
				$modules->addMessage($lang->get('publish-noperm'));
				return false;
				
			}
		
	}
	
	
	/**
	 * Get page skins
	 * 
	 * @param	bool		$active
	 * @return	array
	 */
	
	public function getSkins($active=true)
	{
		// required
			global $cosa, $db;
			$skins = array();
		
		// get skins
			$sql = "SELECT id, name FROM ".$db->module('pages_skins');
			if($active) $sql .= " WHERE active = '1'";
			$sql .= " ORDER BY name";
			$res = mysql_query($sql) or $cosa->oops('Couldn\'t fetch skins.');
		
		// return skins
			while($row = mysql_fetch_array($res, MYSQL_ASSOC)) $skins[] = $row;
			$this->skins = $skins;
			$this->skinsActive = $active;
			return $skins;
		
	}
	
	
	/**
	 * Print skins dropdown
	 * 
	 * @param	string		$name
	 * @param	int			$value
	 * @param	bool		$active
	 * @return	void
	 */
	
	public function printSkinsDropdown($name='skins', $value=false, $active=true)
	{
		// required
			global $cosa, $db;
			$skins = $this->getSkins($active);
		
		// check for multiple
			if(empty($skins)) return false;
			if(count($skins) == 1) echo '<input type="hidden" name="'.$name.'" value="'.$skins[0]['id'].'" />'."\n";
			else {
				echo '<select name="'.$name.'">'."\n\t";
				foreach($skins as $k => $skin) {
					$selected = ($value == $skin['id']) ? ' selected="selected"' : '';
					echo '<option value="'.stripslashes($skin['id']).'"'.$selected.'>'.stripslashes($skin['name']).'</option>'."\n\t";
				}
				echo '</select>'."\n";
			}
		
	}
	
	
	/**
	 * Get the number of skins available
	 * 
	 * @param	bool		$active
	 * @return	int
	 */
	
	public function numSkins($active=true)
	{
		if(!isset($this->skins) || (isset($this->skinsActive) && $this->skinsActive != $active)) $skins = $this->getSkins($active);
		return count($this->skins);
	}
	
	
	/**
	 * Get the original id from a page
	 * 
	 * @param	int		$id
	 * @return	int
	 */
	
	public function getOriginalId($id)
	{
		global $cosa, $db;
		$sql = "SELECT original_id FROM ".$db->module('pages')." WHERE id ='".addslashes($id)."'";
		$res = @mysql_query($sql) or $cosa->kill($lang->get('del-page-failed'), 'db');
		if(!mysql_num_rows($res)) return false;
		$row = mysql_fetch_array($res);
		return stripslashes($row['original_id']);
	}
	
	
	/**
	 * Get FUS keys
	 * 
	 * @param	int		$language_id
	 * @return	array
	 */
	
	public function getFusKeys($language_id=false)
	{
		global $cosa, $db, $lang;
		if(!$language_id) $language_id = $lang->id;
		$keys = array();
		$sql = "SELECT * FROM ".$db->module('pages_fus')." WHERE language_id = '".addslashes($language_id)."' ORDER BY `key`";
		$res = mysql_query($sql) or $cosa->oops('Could not fetch FUS keys.');
		while($row = mysql_fetch_array($res)) $keys[] = $row;
		return $keys;
	}
	
	
	/**
	 * Get value from FUS key id
	 * 
	 * @param	int		$id
	 * @return	string
	 */
	
	public function getFusValue($id)
	{
		global $cosa, $db;
		$sql = "SELECT value FROM ".$db->module('pages_fus')." WHERE id = '".addslashes($id)."' LIMIT 1";
		$res = mysql_query($sql) or $cosa->oops('Could not fetch FUS value.');
		if(!mysql_num_rows($res)) return '-';
		$row = mysql_fetch_array($res);
		return stripslashes($row['value']);
	}
	
	
}

?>